/* AccountsEditorActivity.java
 *
 * Copyright 2011 Aleksey Konovalov
 * All Rights Reserved.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>. 
 * 
 */

package org.jimm.app;

import java.util.ArrayList;
import java.util.List;

import org.jimm.protocol.Profile;
import org.jimm.db.JimmDatabase.Accounts;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.database.ContentObserver;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.text.InputType;
import android.text.TextUtils;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ToggleButton;

/**
 * @author r.u.s.h.a.n.
 */
public class AccountsEditorActivity extends Activity {

    public static final String LOG_TAG = "Jimm:AccountEditor";
    private List<Profile> items = new ArrayList<Profile>();

    private class AccountsObserver extends ContentObserver {

        public AccountsObserver(Handler handler) {
            super(handler);
        }

        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            accountsListAdapter.updateItems();
        }

    }

    private class AccountsAdapter extends BaseAdapter {

        private final LayoutInflater inflater;

        AccountsAdapter(Context context) {
            inflater = LayoutInflater.from(context);
            updateItems();
        }

        public void updateItems() {
            synchronized (items) {
                items.clear();
                Cursor c = managedQuery(Accounts.CONTENT_URI, null, null, null, null);
                if (c != null && c.moveToFirst()) {
                    do {
                        Profile p = new Profile();
                        p.accountId = c.getLong(c.getColumnIndex(Accounts._ID));
                        p.protocolType = c.getInt(c.getColumnIndex(Accounts.TYPE));
                        p.userId = c.getString(c.getColumnIndex(Accounts.LOGIN));
                        p.password = c.getString(c.getColumnIndex(Accounts.PASSWORD));
                        p.nick = c.getString(c.getColumnIndex(Accounts.NICK));
                        p.statusIndex = c.getInt(c.getColumnIndex(Accounts.STATUS_INDEX));
                        p.statusMessage = c.getString(c.getColumnIndex(Accounts.STATUS_MESSAGE));
                        p.isActive = ((c.getInt(c.getColumnIndex(Accounts.FLAGS)) & Accounts.FLAG_ACTIVE) != 0);
                        p.autoConnect = ((c.getInt(c.getColumnIndex(Accounts.FLAGS)) & Accounts.FLAG_AUTOCONNECT) != 0);

                        items.add(p);

                    } while (c.moveToNext());
                }
                notifyDataSetChanged();
            }
        }


        public int getCount() {
            synchronized (items) {
                return items.size();
            }
        }


        @Override
        public Profile getItem(int position) {
            synchronized (items) {
                return items.get(position);
            }
        }

        @Override
        public long getItemId(int position) {
            synchronized (items) {
                return items.get(position).accountId;
            }
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.accounts_list_item, null);
            }

            Profile p = items.get(position);

            ImageView imageProtocol = (ImageView) convertView.findViewById(R.id.account_protocol);
            TextView textLogin = (TextView) convertView.findViewById(R.id.account_login);
            ToggleButton toggleButton = (ToggleButton) convertView.findViewById(R.id.toggle_button);

            imageProtocol.setImageResource(p.getIcon());
            textLogin.setText(p.userId);
            toggleButton.setChecked(p.isActive);
            toggleButton.setFocusableInTouchMode(false);
            toggleButton.setFocusable(false);

            toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    items.get(position).isActive = isChecked;
                }
            });

            return convertView;
        }

    }

    private AccountsAdapter accountsListAdapter;
    private AccountsObserver accountsObserver;

    // FIXME
    class LoginDialog {

        private Dialog dialogLogin;
        private boolean isActive;

        public LoginDialog(final int type, final long id) {
            // FIXME  change type login field
            dialogLogin = new Dialog(AccountsEditorActivity.this);

            dialogLogin.setContentView(R.layout.login);

            final EditText editLogin = (EditText) dialogLogin.findViewById(R.id.Login);
            final EditText editNick = (EditText) dialogLogin.findViewById(R.id.Nick);
            final EditText editPass = (EditText) dialogLogin.findViewById(R.id.Password);
            final CheckBox checkAutoConnect = (CheckBox) dialogLogin.findViewById(R.id.auto_connect);

            if (id != -1) {
                dialogLogin.setTitle(getText(R.string.acc_edit));

                String[] d = new String[]{
                        Accounts.LOGIN,
                        Accounts.PASSWORD,
                        Accounts.NICK,
                        Accounts.FLAGS
                };

                Cursor c = managedQuery(Accounts.CONTENT_URI, d, Accounts._ID + " = " + id, null, null);

                if (c != null && c.moveToFirst()) {
                    editLogin.setText(c.getString(c.getColumnIndex(Accounts.LOGIN)));
                    editNick.setText(c.getString(c.getColumnIndex(Accounts.NICK)));
                    editPass.setText(c.getString(c.getColumnIndex(Accounts.PASSWORD)));
                    checkAutoConnect.setChecked(((c.getInt(c.getColumnIndex(Accounts.FLAGS)) & Accounts.FLAG_AUTOCONNECT) != 0));
                    isActive = ((c.getInt(c.getColumnIndex(Accounts.FLAGS)) & Accounts.FLAG_ACTIVE) != 0);

                }
            } else {
                dialogLogin.setTitle(getText(R.string.acc_add));
            }

            switch (type) {
                case Accounts.PROTOCOL_ICQ:
                    editLogin.setInputType(InputType.TYPE_CLASS_NUMBER);
                    break;
                case Accounts.PROTOCOL_JABBER:
                    editLogin.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
                    break;
            }
            Button buttonOk = (Button) dialogLogin.findViewById(R.id.ButtonOK);
            buttonOk.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    String login = editLogin.getText().toString();
                    String password = editPass.getText().toString();
                    String nick = editNick.getText().toString();

                    if (TextUtils.isEmpty(nick))
                        nick = login;

                    int flags = 0;

                    ContentValues values = new ContentValues();

                    values.put(Accounts.LOGIN, login);
                    values.put(Accounts.PASSWORD, password);
                    values.put(Accounts.NICK, nick);
                    values.put(Accounts.STATUS_MESSAGE, "?");
                    values.put(Accounts.TYPE, type);

                    if (isActive)
                        flags |= Accounts.FLAG_ACTIVE;

                    if (checkAutoConnect.isChecked())
                        flags |= Accounts.FLAG_AUTOCONNECT;

                    values.put(Accounts.FLAGS, flags);

                    if (id != -1) {
                        getContentResolver().update(Accounts.CONTENT_URI, values, "_ID = " + id, null);
                    } else {
                        getContentResolver().insert(Accounts.CONTENT_URI, values);
                    }
                    dialogLogin.dismiss();
                }

            });
            dialogLogin.show();
        }
    }

    void initAccountsList() {
        ListView accountsList = (ListView) findViewById(R.id.AccountsList);
        accountsList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        accountsListAdapter = new AccountsAdapter(this);
        accountsList.setAdapter(accountsListAdapter);
        registerForContextMenu(accountsList);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.accounts_manager);
        setTitle(R.string.acc_editor);

        initAccountsList();
        accountsObserver = new AccountsObserver(new Handler());
        getContentResolver().registerContentObserver(Accounts.CONTENT_URI, true, accountsObserver);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        int n = items.size();

        for (int i = 0; i < n; i++) {

            Profile p = items.get(i);

            int flags = 0;

            if (p.isActive)
                flags |= Accounts.FLAG_ACTIVE;

            if (p.autoConnect)
                flags |= Accounts.FLAG_AUTOCONNECT;

            ContentValues values = new ContentValues();

            values.put(Accounts.LOGIN, p.userId);
            values.put(Accounts.PASSWORD, p.password);
            values.put(Accounts.NICK, p.nick);
            values.put(Accounts.STATUS_INDEX, p.statusIndex);
            values.put(Accounts.STATUS_MESSAGE, p.statusMessage);
            values.put(Accounts.TYPE, p.protocolType);
            values.put(Accounts.FLAGS, flags);

            getContentResolver().update(Accounts.CONTENT_URI, values, "_ID = " + p.accountId, null);
        }
        getContentResolver().unregisterContentObserver(accountsObserver);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.accounts_editor, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.add:
                addAccount();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {

        menu.add(Menu.FIRST, R.id.menu_edit, 0, R.string.edit);
        menu.add(Menu.FIRST, R.id.menu_delete, 0, R.string.delete);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
        final long accountID = accountsListAdapter.getItemId(info.position);
        final String itemName = accountsListAdapter.getItem(info.position).userId;

        switch (item.getItemId()) {

            case R.id.menu_edit:
                new LoginDialog(Accounts.PROTOCOL_ICQ, accountID);
                return true;

            case R.id.menu_delete:
                AlertDialog.Builder builder = new AlertDialog.Builder(AccountsEditorActivity.this);
                builder.setMessage(getString(R.string.acc_delete_confirm) + " " + itemName + "?")
                        .setCancelable(false)
                        .setPositiveButton(android.R.string.yes,
                                new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int id) {
                                        getContentResolver().delete(
                                                ContentUris.withAppendedId(
                                                        Accounts.CONTENT_URI,
                                                        accountID), null, null);
                                    }

                                })
                        .setNegativeButton(android.R.string.no, null)
                        .create()
                        .show();

                return true;
        }
        return false;
    }

    private void addAccount() {
        final String[] items = {"ICQ", "Jabber"};
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.setTitle(R.string.acc_sel_protocol);
        builder.setItems(items, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int item) {
                switch (item) {
                    case 0:
                        // ICQ
                        new LoginDialog(Accounts.PROTOCOL_ICQ, -1);
                        break;
                    case 1:
                        // Jabber
                        //					new LoginDialog(Accounts.PROTOCOL_JABBER, -1);
                        break;
                }
            }
        });

        builder.create().show();
    }
}
